package cn.cmkj.auction.ui;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.MainShuAdapter;
import cn.cmkj.auction.app.BaseActivity;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.http.GoodsCate;
import cn.cmkj.auction.data.http.Shuhua;
import cn.cmkj.auction.data.http.ShuhuaProps;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.ItemClickSupport;
import cn.cmkj.auction.utils.SharedPreferencesUtils;
import cn.cmkj.auction.widget.flowlayout.FlowLayout;
import cn.cmkj.auction.widget.flowlayout.TagAdapter;
import cn.cmkj.auction.widget.flowlayout.TagFlowLayout;
import cn.cmkj.auction.widget.swipeRecyclerView.MySwipeMenuRecyclerView;

/**
 * Created by cunguoyao on 2017/8/13.
 */
@ContentView(R.layout.activity_shuhua_list)
public class ShuhuaListActivity extends BaseActivity implements MySwipeMenuRecyclerView.OnLoadListener, View.OnClickListener, View.OnTouchListener {

    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;

    @ViewInject(R.id.shu_top)
    private LinearLayout topLayout;
    @ViewInject(R.id.shu_r1)
    private RelativeLayout relativeLayout1;
    @ViewInject(R.id.shu_text1)
    private CheckBox textMenu1;
    @ViewInject(R.id.shu_r2)
    private RelativeLayout relativeLayout2;
    @ViewInject(R.id.shu_text2)
    private CheckBox textMenu2;
    @ViewInject(R.id.shu_r3)
    private RelativeLayout relativeLayout3;
    @ViewInject(R.id.shu_text3)
    private CheckBox textMenu3;
    @ViewInject(R.id.swipeRecyclerView)
    private MySwipeMenuRecyclerView swipeRecyclerView;

    private PriceTagAdapter priceTagAdapter;
    private List<ShuhuaProps> priceList;

    private CateTagAdapter cateTagAdapter;
    private List<GoodsCate> cateList;

    private PopupWindow popupWindow;
    private TagFlowLayout tagCate;
    private TagFlowLayout tagPrice;

    private List<Shuhua> mData;
    private MainShuAdapter mainShuAdapter;
    private boolean requesting = false;
    private int page = 1;

    private int orderBy = 1;
    private String chooseCateName;
    private int chooseCate = 23;
    private int choosePrice = 0;
    private List<Integer> chooseCateList = new ArrayList<>();
    private List<Integer> choosePriceList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        mData = new ArrayList<>();
        mainShuAdapter = new MainShuAdapter(this, mData);
        cateList = new ArrayList<>();
        priceList = new ArrayList<>();
        LayoutInflater inflater = LayoutInflater.from(this);
        cateTagAdapter = new CateTagAdapter(inflater, cateList);
        priceTagAdapter = new PriceTagAdapter(inflater, priceList);
        Intent intent = getIntent();
        if(intent != null) {
            chooseCate = getIntent().getIntExtra("chooseCate", chooseCate);
            chooseCateName = getIntent().getStringExtra("chooseCateName");
        }
        if(chooseCateName == null) {
            chooseCateName = "书画";
        }
        initPopup();
        swipeRecyclerView.getRecyclerView().setLayoutManager(new GridLayoutManager(this, 2));
        //((SwipeMenuRecyclerView)swipeRecyclerView.getRecyclerView()).setLongPressDragEnabled(true); // 开启拖拽。
        //((SwipeMenuRecyclerView)swipeRecyclerView.getRecyclerView()).setItemViewSwipeEnabled(true); // 开启滑动删除。
        swipeRecyclerView.setAdapter(mainShuAdapter);
        ItemClickSupport.addTo(swipeRecyclerView.getRecyclerView()).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, View itemView, int position) {
                Shuhua shuhua = mData.get(position);
                Intent intent = new Intent(ShuhuaListActivity.this, ShuhuaDetailActivity.class);
                intent.putExtra("shuhua", shuhua);
                startActivity(intent);
            }
        });
        titleText.setText(chooseCateName);
        titleBack.setOnClickListener(this);
        relativeLayout1.setOnClickListener(this);
        relativeLayout2.setOnClickListener(this);
        relativeLayout3.setOnClickListener(this);
        textMenu1.setOnCheckedChangeListener(new Menu1OnCheckedChangeListener());
        textMenu2.setOnCheckedChangeListener(new Menu2OnCheckedChangeListener());
        textMenu3.setOnCheckedChangeListener(new Menu3OnCheckedChangeListener());
        swipeRecyclerView.setOnLoadListener(this);
        swipeRecyclerView.setRefreshing(true);
    }

    @Override
    public void onRefresh() {
        if(!requesting) {
            page = 1;
            mData.clear();
            mainShuAdapter.notifyDataSetChanged();
            fetchGoodsCat();
        }
    }

    @Override
    public void onLoadMore() {
        if(!requesting) {
            page = page +1;
            LogUtil.e("--onLoadMore:page=" + page);
            fetchData();
        }
    }

    public void fetchGoodsCat() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.goodsBasicCat);
        params.addParameter("page_no", 1);
        params.addParameter("page_size", 100);
        x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
            @Override
            public void success(String s) {
                requesting = false;
                swipeRecyclerView.complete();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(s);
                    JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("datas");
                    List<GoodsCate> temp = GoodsCate.parseFromJsonArray(jsonArray);
                    cateList.clear();
                    cateList.addAll(temp);
                    cateTagAdapter.notifyDataChanged();
                    SharedPreferencesUtils.getInstance(ShuhuaListActivity.this, "Art").putListData("goods_cate", cateList);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                fetchData();
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                requesting = false;
                swipeRecyclerView.complete();
                if(ex != null)ex.printStackTrace();
                LogUtil.e("---onError-----" + "onError");
                Toast.makeText(ShuhuaListActivity.this, TextUtils.isEmpty(msg) ? "请求失败" : msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void cancel(CancelledException cex) {
                requesting = false;
                swipeRecyclerView.complete();
                LogUtil.e("---onCancelled-----" + "onCancelled");
            }
        });
    }

    public void fetchData() {
        requesting = true;
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.goodsSearchList);
        params.addParameter("page_num", page);
        params.addParameter("page_size", Urls.pageSize);
        params.addParameter("cat_id", String.valueOf(chooseCate));//分类id
        params.addParameter("search_keywords", "");
        params.addParameter("brand_id", "");//array(int)数组的json(作者id(原品牌))
        params.addParameter("specs", "");//array(int=>array(int))格式的json 商品规格array(规格id=>array(规格值id))
        params.addParameter("props", "");//array(int=>array(int))格式的json props 商品属性id
        params.addParameter("orderBy_id", String.valueOf(orderBy));//排序 1-默认，2-按发布时间 新->旧，3-按发布时间 旧->新，4-按价格 从高到低，5-按价格 从低到高，6-访问周次数，7-总访问次数，8-周购买次数，9-总购买次数，10-评论次数
        if(choosePrice == 0) {
            params.addParameter("price_range", "");//价格区间 1-(0-99),2-(100-299),3-(300-499),4-(500以上)
        }else {
            params.addParameter("price_range", String.valueOf(choosePrice));
        }
        x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
            @Override
            public void success(String s) {
                requesting = false;
                swipeRecyclerView.complete();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(s);
                    JSONObject json = jsonObject.optJSONObject("data");
                    JSONArray jsonArray = json.optJSONArray("goods");
                    List<Shuhua> temp = Shuhua.parseJsonArray(jsonArray);
                    mData.addAll(temp);
                    mainShuAdapter.notifyDataSetChanged();
                    if(Urls.pageSize > temp.size()) {
                        swipeRecyclerView.setLoadMoreEnable(false);
                    }else {
                        swipeRecyclerView.setLoadMoreEnable(true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                requesting = false;
                swipeRecyclerView.complete();
                if(ex != null)ex.printStackTrace();
                LogUtil.e("---onError-----" + "onError");
                Toast.makeText(ShuhuaListActivity.this, TextUtils.isEmpty(msg) ? "请求失败" : msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void cancel(CancelledException cex) {
                requesting = false;
                swipeRecyclerView.complete();
                LogUtil.e("---onCancelled-----" + "onCancelled");
            }
        });
    }

    private void initPopup() {
        LayoutInflater inflater = LayoutInflater.from(this);
        popupWindow = new PopupWindow(this);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = inflater.inflate(R.layout.pop_shu_menu, null);
        popupWindow.setContentView(view);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x4c000000));
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setOnDismissListener(new MenuPopOnDismissListener());
        tagCate = (TagFlowLayout)view.findViewById(R.id.tag_cate);
        tagPrice = (TagFlowLayout)view.findViewById(R.id.tag_price);
        tagCate.setMaxSelectCount(1);
        tagPrice.setMaxSelectCount(1);
        List<GoodsCate> goodsCateList = SharedPreferencesUtils.getInstance(this, "Art").getListData("goods_cate", GoodsCate.class);
        cateList.clear();
        cateList.addAll(goodsCateList);
        ShuhuaProps price0 = new ShuhuaProps("0", "全部");
        ShuhuaProps price1 = new ShuhuaProps("1", "0~500");
        ShuhuaProps price2 = new ShuhuaProps("2", "500~2000");
        ShuhuaProps price3 = new ShuhuaProps("3", "2000~5000");
        ShuhuaProps price4 = new ShuhuaProps("4", "5000~10000");
        ShuhuaProps price5 = new ShuhuaProps("5", "10000以上");
        priceList.clear();
        priceList.add(price0);
        priceList.add(price1);
        priceList.add(price2);
        priceList.add(price3);
        priceList.add(price4);
        priceList.add(price5);
        if(cateList.size() > 0) {
            cateTagAdapter.setSelected(0, cateList.get(0));
        }
        if(priceList.size() > 0) {
            priceTagAdapter.setSelected(0, priceList.get(0));
        }
        tagCate.setAdapter(cateTagAdapter);
        tagPrice.setAdapter(priceTagAdapter);
    }

    class CateTagAdapter extends TagAdapter<GoodsCate> {
        private LayoutInflater inflater;
        public CateTagAdapter(LayoutInflater inflater, List<GoodsCate> cateList) {
            super(cateList);
            this.inflater = inflater;
        }

        @Override
        public View getView(FlowLayout parent, int position, GoodsCate s) {
            TextView tv = (TextView) inflater.inflate(R.layout.view_shu_menu_item, tagCate, false);
            tv.setText(s.cat_name);
            return tv;
        }

        @Override
        public void onSelected(int position, View view) {
            super.onSelected(position, view);
            GoodsCate goodsCate = cateList.get(position);
            chooseCateList.clear();//单选菜单要clear
            if(!chooseCateList.contains(goodsCate.cat_id)) {
                chooseCateList.add(goodsCate.cat_id);
            }
        }
    }

    class PriceTagAdapter extends TagAdapter<ShuhuaProps> {
        private LayoutInflater inflater;
        public PriceTagAdapter(LayoutInflater inflater, List<ShuhuaProps> cateList) {
            super(cateList);
            this.inflater = inflater;
        }

        @Override
        public View getView(FlowLayout parent, int position, ShuhuaProps s) {
            TextView tv = (TextView) inflater.inflate(R.layout.view_shu_menu_item, tagPrice, false);
            tv.setText(s.value);
            return tv;
        }

        @Override
        public void onSelected(int position, View view) {
            super.onSelected(position, view);
            ShuhuaProps shuhuaProps = priceList.get(position);
            Integer propId = Integer.valueOf(shuhuaProps.name);
            choosePriceList.clear();//单选菜单要clear
            if(!choosePriceList.contains(propId)) {
                choosePriceList.add(propId);
            }
        }
    }

    private class Menu1OnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked) {
            }
        }
    }

    private class Menu2OnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked) {
                orderBy = 5;
            }else {
                orderBy = 4;
            }
            onRefresh();
        }
    }

    private class Menu3OnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked) {
                if(popupWindow != null && !popupWindow.isShowing()) {
                    popupWindow.showAsDropDown(topLayout);
                    backgroundAlpha(1f);
                }
            }else {
                if(popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        }
    }

    private class MenuPopOnDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            textMenu3.setChecked(false);
            backgroundAlpha(1f);
            int cateTmp = 23;
            int priceTmp = 0;
            if(chooseCateList.size() > 0) {
                cateTmp = chooseCateList.get(0);
            }
            if(choosePriceList.size() > 0) {
                priceTmp = choosePriceList.get(0);
            }
            if(chooseCate != cateTmp || choosePrice != priceTmp) {
                chooseCate = cateTmp;
                choosePrice = priceTmp;
                page = 1;
                mData.clear();
                mainShuAdapter.notifyDataSetChanged();
                fetchData();
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.shu_r1:
                textMenu1.setChecked(true);
                break;
            case R.id.shu_r2:
                textMenu2.setChecked(true);
                break;
            case R.id.shu_r3:
                textMenu3.setChecked(true);
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (requesting) {
            return true;
        } else {
            return false;
        }
    }

    public void backgroundAlpha(float bgAlpha) {
        if(this == null)return;
        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        window.setAttributes(lp);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
